package com.zckj.jcServer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandle extends SimpleChannelInboundHandler<ByteBuf> {

	private int counter;

	private byte[] req;

	public  ClientHandle(String data ) {
		req = (data+System.getProperty("line.separator")).getBytes();
//		firstMessage = Unpooled.buffer(req.length);
//		firstMessage.writeBytes(req);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		ByteBuf message = null;
//		for (int i = 0; i < 10000; i++) {
//		}
		message = Unpooled.buffer(req.length);
		message.writeBytes(req);
		ctx.writeAndFlush(message);
		// ctx.writeAndFlush(Unpooled.copiedBuffer("Netty
		// rocks!",CharsetUtil.UTF_8));
	}

	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("Client receive Now is Body :" + body + "; the counter is " + ++counter);
		// System.out.println("Client received:
		// "+buf.toString(CharsetUtil.UTF_8));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// 释放资源
//		log.warn("不期望的异常信息" + cause.getMessage());
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		String body = (String) msg;
		System.out.println("Client receive Now is Body :" + body + "; the counter is " + ++counter);
	}
}
